import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class FocusWidget extends StatefulWidget {
  final Widget child;
  final FocusNode focusNode;
  final bool? autofocus;
  final void Function()? onConfirm;
  final void Function(bool value)? onFocusChange;
  final FocusOnKeyEventCallback? onKeyEvent;

  FocusWidget(
      {super.key,
      required this.child,
      FocusNode? focusNode,
      this.autofocus,
      this.onConfirm,
      this.onKeyEvent,
      this.onFocusChange})
      : focusNode = focusNode ?? FocusNode();

  @override
  State<FocusWidget> createState() => _FocusWidgetState();
}

class _FocusWidgetState extends State<FocusWidget> {
  @override
  Widget build(BuildContext context) {
    return Focus(
      focusNode: widget.focusNode,
      autofocus: widget.autofocus ?? false,
      onFocusChange: widget.onFocusChange,
      child: GestureDetector(
        onTap: () {
          widget.focusNode.requestFocus();
          widget.onConfirm?.call();
        },
        child: widget.child,
      ),
      onKeyEvent: (node, event) {
        KeyEventResult result = KeyEventResult.ignored;
        if (event is KeyDownEvent &&
            (event.logicalKey == LogicalKeyboardKey.enter ||
                event.logicalKey == LogicalKeyboardKey.select)) {
          widget.onConfirm?.call();
          result = KeyEventResult.handled;
        }
        return widget.onKeyEvent?.call(node, event) ?? result;
      },
    );
  }
}
